﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using SIMSProject.Common;
using SIMSProject.WebParts;

namespace SIMSProject.Helpers.QuickLaunch
{
    class QuickLaunchManager
    {
        internal const string VisibleContextCookieName = "SIMS.SharePoint.QuickLaunch.VisibleContext";

        public static void CreateQuickLaunchDataSource(SPWeb web)
        {
            SPList qlList = web.Lists.TryGetList(Constant.QuickLaunchListName);

            if (qlList != null)
            {
                qlList.Delete();
            }

            ListHelper helper = new ListHelper(web) { Title = Constant.QuickLaunchListName };

            helper.AddField(new SingleLineTextFieldCreator("Description"));
            helper.AddField(new SingleLineTextFieldCreator("Url"));
            helper.AddField(new NumberFieldCreator("Position") { Required = true });
            helper.AddField(new LookupFieldCreator("ParentId") { LookupList = Constant.QuickLaunchListName, LookupField = "ID" });
            helper.AddField(new SingleLineTextFieldCreator("ListId"));
            helper.AddField(new SingleLineTextFieldCreator("PermissionLevels"));
            helper.AddField(new BooleanFieldCreator("VisibleForAdminOnly"));
            helper.AddField(new BooleanFieldCreator("IsExternalUrl"));
            helper.AddField(new SingleLineTextFieldCreator("VisibleContext"));
            helper.AddField(new BooleanFieldCreator("SetVisibleContext"));
            helper.AddField(new SingleLineTextFieldCreator("TargetVisibleContext"));
            helper.AddField(new BooleanFieldCreator("DefaultCollapsed"));
            qlList = helper.Apply();

            qlList.Hidden = true;
            qlList.Update();

            // Create a page
            WebPageHelper.CreateDefaultWebPage(web, "QuickLaunchManager.aspx", true);
            WebPartHelper.AddWebPart(web, "QuickLaunchManager.aspx", new QuickLaunchManagerWebPart { Title = "Quick Launch Manager WebPart" }, "Main", 0);

            WebPageHelper.CreateDefaultWebPage(web, "QuickLaunchItem.aspx", true);
            WebPartHelper.AddWebPart(web, "QuickLaunchItem.aspx", new QuickLaunchItemWebPart { Title = "Quick Launch Item WebPart" }, "Main", 0);

            WebPageHelper.CreateDefaultWebPage(web, "QuickLaunchContext.aspx", true);
            WebPartHelper.AddWebPart(web, "QuickLaunchContext.aspx", new QuickLaunchContextWebPart { Title = "Quick Launch Context WebPart" }, "Main", 0);
        }

        public static int AddNavigationLink(SPWeb web, QuickLaunchItem item, int parentId)
        {
            if (parentId < 0)
            {
                throw new ArgumentOutOfRangeException("parentId", "The parent id can not less than 0");
            }

            SPList list = web.Lists[Constant.QuickLaunchListName];
            SPListItem listItem = list.AddItem();

            listItem["Title"] = item.Title;
            listItem["Description"] = item.Description;

            if (string.IsNullOrEmpty(item.Url) && !item.SetVisibleContext)
            {
                listItem["Url"] = "javascript:void(0)";
                listItem["IsExternalUrl"] = true;
            }
            else
            {
                listItem["Url"] = item.Url;
                listItem["IsExternalUrl"] = item.IsExternalUrl;
            }

            listItem["Position"] = item.Position;

            if (parentId > 0)
            {
                listItem["ParentId"] = parentId;
            }

            listItem["ListId"] = item.ListId;
            listItem["PermissionLevels"] = item.PermissionLevels;

            listItem["VisibleContext"] = item.VisibleContext;
            listItem["SetVisibleContext"] = item.SetVisibleContext;
            listItem["TargetVisibleContext"] = item.TargetVisibleContext;

            if (parentId == 0)
            {
                listItem["DefaultCollapsed"] = item.DefaultCollapsed;
            }

            listItem.Update();

            // Update id
            item.Id = listItem.ID;

            return listItem.ID;
        }

        public static int AddHeading(SPWeb web, QuickLaunchItem item)
        {
            return AddNavigationLink(web, item, 0);
        }

        public static IList<QuickLaunchItem> GetAllQuickLaunchHeading(SPWeb web)
        {
            return GetAllQuickLaunchItems(web).Where(item => item.ParentId == 0).OrderBy(item => item.Title).ToList();
        }

        public static IList<QuickLaunchItem> GetAllQuickLaunchItems(SPWeb web)
        {
            if (!web.DoesUserHavePermissions(SPBasePermissions.ManageWeb))
            {
                return GetAllQuickLaunchItems(web.Site.ID, web.ID);
            }

            var list = web.Lists[Constant.QuickLaunchListName];
            return (from SPListItem item in list.Items select new QuickLaunchItem(item)).ToList();
        }

        private static IList<QuickLaunchItem> GetAllQuickLaunchItems(Guid siteId, Guid webId)
        {
            IList<QuickLaunchItem> items = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.OpenWeb(webId))
                    {
                        items = GetAllQuickLaunchItems(web);
                    }
                }
            });
            return items;
        }

        public static QuickLaunchItem GetQuickLaunchItem(SPWeb web, int id)
        {
            if (!web.DoesUserHavePermissions(SPBasePermissions.ManageWeb))
            {
                return GetQuickLaunchItem(web.Site.ID, web.ID, id);
            }

            var list = web.Lists[Constant.QuickLaunchListName];
            return new QuickLaunchItem(list.GetItemById(id));
        }

        private static QuickLaunchItem GetQuickLaunchItem(Guid siteId, Guid webId, int id)
        {
            QuickLaunchItem item = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.OpenWeb(webId))
                    {
                        item = GetQuickLaunchItem(web, id);
                    }
                }
            });
            return item;
        }
    }
}
